<template>
    <div class="favorites-container">
      <div class="banner">
        <div class="banner-content">
          <h1>我的收藏</h1>
          <p>珍藏您喜爱的京剧经典作品</p>
        </div>
      </div>
      
      <div class="content-section">
        <div class="filter-bar">
          <div class="total-count">
            共收藏了 <span class="count-num">{{ total }}</span> 部剧目
          </div>
          <div class="sort-options">
            <span class="sort-label">排序方式：</span>
            <el-radio-group v-model="sortType" size="small" @change="handleSortChange">
              <el-radio-button label="time">收藏时间</el-radio-button>
              <el-radio-button label="name">剧目名称</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <div v-loading="loading" class="drama-grid">
          <template v-if="favoriteList.length > 0">
            <div 
              v-for="drama in favoriteList" 
              :key="drama.dramaId" 
              class="drama-card">
              <div class="drama-cover" @click="viewDramaDetail(drama)">
                <img :src="drama.imageUrl" alt="剧目封面" class="cover-image">
                <div class="drama-type-tags">
                  <el-tag 
                    v-for="typeId in getTypeIds(drama.programtypeId)"
                    :key="typeId"
                    size="mini" 
                    type="success">
                    {{ getTypeName(typeId) }}
                  </el-tag>
                </div>
              </div>
              <div class="drama-info">
                <h3 class="drama-name" @click="viewDramaDetail(drama)">{{ drama.dramaName }}</h3>
                <p class="drama-description">{{ drama.description | truncate }}</p>
                <div class="drama-actions">
                  <span class="favorite-time">收藏于 {{ formatTime(drama.bookmarkTime) }}</span>
                  <el-button type="danger" size="mini" icon="el-icon-delete" circle 
                    @click="removeFavorite(drama)" class="remove-btn"
                    title="取消收藏"></el-button>
                </div>
              </div>
            </div>
          </template>
          
          <div v-if="favoriteList.length === 0 && !loading" class="empty-state">
            <i class="el-icon-star-off"></i>
            <p>您还没有收藏任何剧目</p>
            <el-button type="primary" @click="goToClassics">浏览经典剧目</el-button>
          </div>
        </div>
  
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[12, 24, 36, 48]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
      
      <!-- 剧目详情对话框 -->
      <el-dialog
        :title="currentDrama ? currentDrama.dramaName : ''"
        :visible.sync="dramaDetailVisible"
        width="70%"
        :fullscreen="false"
        class="drama-detail-dialog">
        <div v-if="currentDrama" class="drama-detail">
          <div class="drama-detail-header">
            <div class="drama-detail-cover">
              <img :src="currentDrama.imageUrl || '/images/default-drama.jpg'" alt="剧目封面" class="detail-cover-image">
            </div>
            <div class="drama-detail-info">
              <h2 class="drama-detail-name">{{ currentDrama.dramaName }}</h2>
              <div class="drama-detail-tags">
                <el-tag 
                  v-for="typeId in getTypeIds(currentDrama.programtypeId)"
                  :key="typeId"
                  size="small" 
                  type="success">
                  {{ getTypeName(typeId) }}
                </el-tag>
              </div>
              <div class="drama-detail-description">
                <h4>剧目简介</h4>
                <p>{{ currentDrama.description }}</p>
              </div>
            </div>
          </div>
          
          <el-tabs v-model="activeTab" class="drama-media-tabs">
            <el-tab-pane label="视频资源" name="video">
              <div v-if="currentDrama.videoList && currentDrama.videoList.length > 0" class="video-list">
                <div 
                  v-for="video in currentDrama.videoList" 
                  :key="video.videoId"
                  class="video-item"
                  @click="playVideo(video)">
                  <div class="video-thumb">
                    <i class="el-icon-video-play play-icon"></i>
                  </div>
                  <div class="video-info">
                    <h4 class="video-name">{{ video.videoName }}</h4>
                    <p class="video-description">{{ video.description }}</p>
                  </div>
                </div>
              </div>
              <div v-else class="no-media">
                <i class="el-icon-video-camera"></i>
                <p>暂无视频资源</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="音频资源" name="audio">
              <div v-if="currentDrama.audioList && currentDrama.audioList.length > 0" class="audio-list">
                <div 
                  v-for="audio in currentDrama.audioList" 
                  :key="audio.audioId"
                  class="audio-item">
                  <div class="audio-icon">
                    <i class="el-icon-headset"></i>
                  </div>
                  <div class="audio-info">
                    <h4 class="audio-name">{{ audio.audioName }}</h4>
                    <p class="audio-description">{{ audio.description }}</p>
                  </div>
                  <div class="audio-controls">
                    <el-button type="text" size="mini" @click="playAudio(audio)">
                      <i class="el-icon-video-play"></i> 播放
                    </el-button>
                  </div>
                </div>
              </div>
              <div v-else class="no-media">
                <i class="el-icon-headset"></i>
                <p>暂无音频资源</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>
      
      <!-- 视频播放对话框 -->
      <el-dialog
        title="视频播放"
        :visible.sync="videoPlayerVisible"
        width="80%"
        :fullscreen="false"
        class="video-player-dialog"
        @closed="stopVideo">
        <div v-if="currentVideo" class="video-player-container">
          <h3 class="video-player-title">{{ currentVideo.videoName }}</h3>
          <video 
            ref="videoPlayer"
            class="video-player"
            controls
            autoplay
            :src="currentVideo.videoUrl">
            您的浏览器不支持 HTML5 视频播放
          </video>
          <p class="video-player-description">{{ currentVideo.description }}</p>
        </div>
      </el-dialog>
  
      <!-- 音频播放器 -->
      <div class="audio-player-fixed" v-if="isAudioPlaying">
        <div class="audio-player-info">
          <div class="audio-player-icon">
            <i class="el-icon-headset"></i>
          </div>
          <div class="audio-player-text">
            <h4 class="audio-player-title">{{ currentAudio.audioName }}</h4>
            <audio 
              ref="audioPlayer" 
              :src="currentAudio.audioUrl" 
              autoplay 
              controls
              class="audio-element"
              @ended="stopAudio">
              您的浏览器不支持 HTML5 音频播放
            </audio>
          </div>
        </div>
        <el-button type="danger" circle size="mini" @click="stopAudio" class="close-audio-btn">
          <i class="el-icon-close"></i>
        </el-button>
      </div>
    </div>
  </template>
  
  <script>
  import service from '@/utils/request'
  
  export default {
    name: 'BookMarkVue',
    filters: {
      truncate(value) {
        if (!value) return '';
        if (value.length <= 100) return value;
        return value.substring(0, 100) + '...';
      }
    },
    data() {
      return {
        loading: false,
        favoriteList: [],
        currentPage: 1,
        pageSize: 12,
        total: 0,
        programTypeList: [],
        dramaDetailVisible: false,
        currentDrama: null,
        activeTab: 'video',
        videoPlayerVisible: false,
        currentVideo: null,
        isAudioPlaying: false,
        currentAudio: null,
        sortType: 'time', // 排序方式：time - 收藏时间，name - 剧目名称
      };
    },
    created() {
      document.title = '京剧苑 - 我的收藏';
      window.scrollTo(0, 0);
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        this.fetchProgramTypes();
        this.fetchFavorites();
      },
      
      formatTime(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      },
      
      fetchProgramTypes() {
        service.get('/api/content/program/getProgramTypes').then(res => {
          if (res.code === 200) {
            this.programTypeList = res.data;
          } else {
            this.$message.error('获取节目类型失败');
          }
        }).catch(err => {
          this.$message.error('获取节目类型失败：' + err.message);
        });
      },
      
      fetchFavorites() {
        this.loading = true;
        
        // 检查用户是否登录
        const token = localStorage.getItem('token');
        if (!token) {
          this.$message.warning('请先登录');
          this.$router.push('/login');
          this.loading = false;
          return;
        }
        
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          sortType: this.sortType,
          token: localStorage.getItem('token')
        };
        
        service.get('/api/content/drama/getFavorites', { params })
          .then(res => {
            if (res.code === 200) {
              this.favoriteList = res.data.list || [];
              console.log(this.favoriteList);
              this.total = res.data.total || 0;
              
              // 如果当前页没有数据但总数大于0，回到上一页
              if (this.favoriteList.length === 0 && this.total > 0 && this.currentPage > 1) {
                this.currentPage -= 1;
                this.fetchFavorites();
                return;
              }
            } else {
              this.$message.error(res.message || '获取收藏列表失败');
            }
          })
          .catch(err => {
            console.error('获取收藏列表出错:', err);
            this.$message.error('获取收藏列表失败，请检查网络连接');
          })
          .finally(() => {
            this.loading = false;
          });
      },
      
      handleSizeChange(val) {
        this.pageSize = val;
        this.fetchFavorites();
      },
      
      handleCurrentChange(val) {
        this.currentPage = val;
        this.fetchFavorites();
      },
      
      handleSortChange() {
        this.currentPage = 1;
        this.fetchFavorites();
      },
      
      getTypeIds(typeString) {
        if (!typeString) return [];
        return typeString.split(',');
      },
      
      getTypeName(typeId) {
        const type = this.programTypeList.find(item => item.programTypeId === typeId);
        return type ? type.programTypeName : '';
      },
      
      removeFavorite(drama) {
        const params = {
          dramaId: drama.dramaId,
          token: localStorage.getItem('token')
        };
        this.$confirm('确定要取消收藏该剧目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'

        }).then(() => {
          service.post('/api/content/drama/unfavorite', params).then(res => {
            if (res.code === 200) {
              this.$message.success('已取消收藏');
              this.fetchFavorites(); // 重新加载收藏列表
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(err => {
            console.error('取消收藏失败:', err);
            this.$message.error('操作失败，请稍后重试');
          });
        }).catch(() => {
          // 取消操作
        });
      },
      
      viewDramaDetail(drama) {
        // 显示加载状态
        const loading = this.$loading({
          lock: true,
          text: '正在加载剧目详情...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 获取详细信息
        service.get(`/api/content/drama/getDrama/${drama.dramaId}`)
          .then(res => {
            if (res.code === 200) {
              this.currentDrama = res.data;
              this.dramaDetailVisible = true;
            } else {
              this.$message.error(res.message || '获取剧目详情失败');
            }
          })
          .catch(err => {
            console.error('获取剧目详情出错:', err);
            this.$message.error('获取剧目详情失败，请检查网络连接');
          })
          .finally(() => {
            loading.close();
          });
      },
      
      playVideo(video) {
        this.currentVideo = video;
        this.videoPlayerVisible = true;
      },
      
      stopVideo() {
        if (this.$refs.videoPlayer) {
          this.$refs.videoPlayer.pause();
        }
        this.currentVideo = null;
      },
      
      playAudio(audio) {
        this.stopAudio(); // 停止当前播放的音频
        this.currentAudio = audio;
        this.isAudioPlaying = true;
        this.$nextTick(() => {
          if (this.$refs.audioPlayer) {
            this.$refs.audioPlayer.play();
          }
        });
      },
      
      stopAudio() {
        if (this.isAudioPlaying && this.$refs.audioPlayer) {
          this.$refs.audioPlayer.pause();
        }
        this.isAudioPlaying = false;
        this.currentAudio = null;
      },
      
      goToClassics() {
        this.$router.push('/classics');
      }
    }
  }
  </script>
  
  <style scoped>
  .favorites-container {
    min-height: 100vh;
    padding-bottom: 50px;
    background-color: #f9f5f0;
  }
  
  .banner {
    height: 500px;
    background-image: url('../assets/opera_5.jpg');
    background-size: cover;
    background-position: center;
    position: relative;
    margin-bottom: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .banner:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to bottom, rgba(139, 0, 0, 0.7), rgba(0, 0, 0, 0.5));
  }
  
  .banner-content {
    position: relative;
    z-index: 1;
    text-align: center;
    color: white;
  }
  
  .banner-content h1 {
    font-size: 4rem;
    font-family: 'STXingkai', 'STZhongsong', serif;
    margin-bottom: 15px;
    text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.6);
    color: #FFD700;
    letter-spacing: 10px;
  }
  
  .banner-content p {
    font-size: 1.4rem;
    max-width: 600px;
    margin: 0 auto;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.6);
    letter-spacing: 3px;
  }
  
  .content-section {
    padding: 30px 8%;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    background-color: #fff;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }
  
  .total-count {
    font-size: 1.1rem;
    color: #666;
  }
  
  .count-num {
    font-weight: bold;
    color: #8B0000;
    font-size: 1.3rem;
    margin: 0 3px;
  }
  
  .sort-options {
    display: flex;
    align-items: center;
  }
  
  .sort-label {
    font-size: 1rem;
    color: #666;
    margin-right: 10px;
  }
  
  .drama-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 30px;
    margin-bottom: 30px;
  }
  
  .drama-card {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: none;
  }
  
  .drama-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(139, 0, 0, 0.15);
  }
  
  .drama-cover {
    position: relative;
    width: 100%;
    padding-top: 75%; /* 4:3 比例 */
    overflow: hidden;
    cursor: pointer;
  }
  
  .cover-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
  }
  
  .drama-card:hover .cover-image {
    transform: scale(1.05);
  }
  
  .drama-type-tags {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    justify-content: flex-end;
  }
  
  .drama-info {
    padding: 1.2rem;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
  }
  
  .drama-name {
    font-size: 1.2rem;
    margin: 0 0 0.8rem;
    color: #333;
    font-weight: 600;
    cursor: pointer;
    transition: color 0.3s ease;
  }
  
  .drama-name:hover {
    color: #8B0000;
  }
  
  .drama-description {
    color: #666;
    font-size: 0.9rem;
    line-height: 1.5;
    margin: 0 0 1rem;
    flex-grow: 1;
  }
  
  .drama-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: auto;
  }
  
  .favorite-time {
    font-size: 0.8rem;
    color: #999;
  }
  
  .remove-btn {
    transition: all 0.3s ease;
  }
  
  .remove-btn:hover {
    background-color: #F56C6C;
    color: #fff;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 10px 0;
  }
  
  .empty-state {
    text-align: center;
    padding: 60px 0;
    color: #999;
    background: #fff;
    border-radius: 8px;
    margin: 20px 0;
    grid-column: 1 / -1;
  }
  
  .empty-state i {
    font-size: 4rem;
    margin-bottom: 20px;
    color: #ddd;
  }
  
  .empty-state p {
    font-size: 1.3rem;
    margin-bottom: 25px;
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .banner {
      height: 240px;
    }
    
    .banner-content h1 {
      font-size: 2.5rem;
      letter-spacing: 5px;
    }
    
    .banner-content p {
      font-size: 1.2rem;
      letter-spacing: 1px;
    }
    
    .filter-bar {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .content-section {
      padding: 20px 3%;
    }
  }
  
  @media (max-width: 480px) {
    .banner-content h1 {
      font-size: 2rem;
      letter-spacing: 3px;
    }
    
    .banner-content p {
      font-size: 1rem;
    }
  }
  </style>